﻿using System;
using System.Reflection;
using Tofu.Core;
using Tofu.Data;
using System.Linq;
using Tofu.Core.Prototype;

namespace Tofu.Services
{

    public class DataService
    {

        private static readonly Lazy<TofuDataSourceDataContext> _instance = new Lazy<TofuDataSourceDataContext>(() => new TofuDataSourceDataContext());

        public static TofuDataSourceDataContext Db
        {
            get { return _instance.Value; }
        }

        public static T1 Convert<T1, T2>(T2 entity)
            where T1 : class, new()
            where T2 : class
        {
            var t1 = new T1();
            foreach (var property in typeof(T1).GetProperties())
            {
                if (property.CustomAttributes.Any(ca => ca.AttributeType.Equals(typeof(ColumnAttribute))))
                {
                    var members = entity.GetType().GetMember(property.Name);
                    if (members.Any())
                    {
                        var value = ((PropertyInfo)members[0]).GetValue(entity);
                        t1.GetType().GetProperty(property.Name).SetValue(t1, value);                        
                    }
                }
            }
            return t1;
        }

    }

}